/* 
 * 功能：vxe-grid 行拖动
 * 参数：
 */
import XEUtils from "xe-utils";
import Sortable from "sortablejs";

export default {
    inserted: (el, binding, vnode, oldVnode) => {
        let xTable = vnode.child;   //VueComponent实例
        Sortable.create(xTable.$el.querySelector('.body--wrapper>.vxe-table--body tbody'), {
            handle: '.drag-btn',
            onEnd: ({ item, oldIndex }) => {
                let options = { children: 'children' }
                let targetTrElem = item
                let wrapperElem = targetTrElem.parentNode
                let prevTrElem = targetTrElem.previousElementSibling
                //let tableTreeData = this.tableTreeData
                let selfRow = xTable.getRowNode(targetTrElem).item
                let selfNode = XEUtils.findTree(tableTreeData, row => row === selfRow, options)
                if (prevTrElem) {
                    // 移动到节点
                    let prevRow = xTable.getRowNode(prevTrElem).item
                    let prevNode = XEUtils.findTree(tableTreeData, row => row === prevRow, options)
                    if (XEUtils.findTree(selfRow[options.children], row => prevRow === row, options)) {
                        // 错误的移动
                        let oldTrElem = wrapperElem.children[oldIndex]
                        wrapperElem.insertBefore(targetTrElem, oldTrElem)
                        this.$XModal.message({ message: '不允许自己给自己拖动！', status: 'error' })
                    }
                    let currRow = selfNode.items.splice(selfNode.index, 1)[0]
                    if (xTable.isTreeExpandByRow(prevRow)) {
                        // 移动到当前的子节点
                        prevRow[options.children].splice(0, 0, currRow)
                    } else {
                        // 移动到相邻节点
                        prevNode.items.splice(prevNode.index + (selfNode.index < prevNode.index ? 0 : 1), 0, currRow)
                    }
                } else {
                    // 移动到第一行
                    var currRow = selfNode.items.splice(selfNode.index, 1)[0]
                    tableTreeData.unshift(currRow)
                }
                // 如果变动了树层级，需要刷新数据
                xTable.syncData()
            }
        })
    }
}